package cn.work.control;

import cn.work.service.ClassService;
import cn.work.service.goodsService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ServiceClassAddServlet", value = "/ServiceClassAddServlet")
public class ServiceClassAddServlet extends HttpServlet {
    private ClassService cdao = new ClassService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String className = request.getParameter("classname");
        System.out.println("Received request to add category: " + className);

        if (className == null || className.trim().isEmpty()) {
            request.setAttribute("error", "分类名称不能为空！");
            request.getRequestDispatcher("admin/servlet_class.jsp").forward(request, response);
            return;
        }

        boolean success = cdao.addCategory(className);
        
        if (success) {
            System.out.println("Category added successfully: " + className);
            response.sendRedirect(request.getContextPath() + "admin/servlet_class.jsp");
        } else {
            System.out.println("Failed to add category: " + className);
            request.setAttribute("error", "分类添加失败，请重试！");
            request.getRequestDispatcher("admin/servlet_class.jsp").forward(request, response);
        }
        response.sendRedirect("admin/servlet_class.jsp");
    }
}
